import got from 'got';
import { NextApiRequest, NextApiResponse } from 'next';

type Arch = 'x64.dmg' | 'arm64.dmg' | 'x64.exe' | 'ia32.exe' | 'deb';

interface Asset {
  name: string
  browser_download_url: string
}

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const {arch} = req.query as { arch: Arch };
  if (!['x64.dmg', 'arm64.dmg', 'x64.exe', 'ia32.exe', 'deb'].includes(arch)) {
    return res.status(400).send(`Unrecognized arch "${arch}". Expected win or mac or linux.`);
  }

  const {body} = await got.get<{assets?: Asset[]}>('https://api.github.com/repos/rubickCenter/rubick/releases/latest', {
    responseType: 'json'
  });

  const assets = body.assets ?? [];

  const dmgArtifact = getAssets(arch, assets);
  const dmgLink = dmgArtifact?.browser_download_url;
  if (dmgLink) {
    res.writeHead(302, {
      Location: dmgLink
    });
    res.end();
  } else {
    res.status(404);
    res.send('未找到产物！');
  }
}

function getAssets(arch, assets: Asset[]) {
  return assets.find(asset => asset.name.indexOf(arch) !== -1);
}
